package com.yubest;

/**
 * [图片] img/fast.png
 * 快速幂
 *
 * @Author hweiyu
 * @Description
 * @Date 2021/11/15 16:08
 */
public class FastPower {

    public static void main(String[] args) {
        System.out.println((int) Math.pow(0, 2) + ", " + new FastPower().power(0, 2));

        System.out.println((int) Math.pow(1, 2) + ", " + new FastPower().power(1, 2));

        System.out.println((int) Math.pow(8, 5) + ", " + new FastPower().power(8, 5));

        System.out.println(8 * 11 + ", " + new FastPower().mul(8, 11));
    }

    /**
     * 快速幂
     *
     * 计算x的y次方
     *
     * @param x
     * @param y
     * @return
     */
    public int power(int x, int y) {
        if (y == 0) {
            return 1;
        }
        int r = 1;
        while (y > 0) {
            if ((y & 1) > 0) {
                r *= x;
            }
            y >>= 1;
            x *= x;
        }
        return r;
    }

    /**
     * 快速乘
     * @param x
     * @param y
     * @return
     */
    public int mul(int x, int y) {
        if (y == 0) {
            return 0;
        }
        int r = 0;
        while (y > 0) {
            if ((y & 1) > 0) {
                r += x;
            }
            y >>= 1;
            x += x;
        }
        return r;
    }
}
